import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import microApp,{EventCenterForMicroApp} from '@micro-zoe/micro-app'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './styles/global.css'

// 将 microApp 注入到 window 对象
declare global {
  interface Window {
    microApp: typeof microApp;
    __MICRO_APP_ENVIRONMENT__: boolean;
    __MICRO_APP_PUBLIC_PATH__: string;
    __MICRO_APP_BASE_ROUTE__: string;
    __MICRO_APP_NAME__: string;
    eventCenterForChildApp: any;
  }
}

//必须在此处将microApp挂载在window对象
window.microApp = microApp

//设置全局数据
microApp.setGlobalData({"type": '全局数据-ABC',"token":"xxxxxxxx"});

// 只保留一个全局数据监听器
microApp.addGlobalDataListener((data: any) => {
  // 判断数据来源，避免自己发送的消息被自己接收
  console.log('[主应用]收到全局数据:', data);
  return true;
});

// 创建全局数据通信对象
window.eventCenterForChildApp = new EventCenterForMicroApp('child-app')

// 监听子应用消息
window.eventCenterForChildApp.addDataListener((data: any) => {
  console.log('[主应用] ====== 收到子应用消息 ======')
  console.log('[主应用] 数据类型:', data?.type)
  console.log('[主应用] 数据内容:', data?.data)
});

// 开启调试模式
microApp.start({
  plugins: {
    modules: {
      'child-app': [
        {
          processHtml(code) {
            const injectScript = `
              <script>
                window.__MICRO_APP_ENVIRONMENT__ = true;
                window.__MICRO_APP_PUBLIC_PATH__ = '${window.location.origin}/child/';
                window.__MICRO_APP_BASE_ROUTE__ = '/child';
                window.microApp = window.parent.microApp;
              </script>
            `
            return code.replace('<head>', `<head>${injectScript}`)
          },
          loader(code) {
            if (import.meta.env.DEV) {
              code = code.replace(/(from|import)(\s*['"])(\/)/g, (all) => {
                return all.replace('/', '/child-app/')
              })
            }
            return code
          }
        }
      ],
      'react-app': [
        {
          processHtml(code) {
            const injectScript = `
              <script>
                window.__MICRO_APP_ENVIRONMENT__ = true;
                window.__MICRO_APP_PUBLIC_PATH__ = '${window.location.origin}/react-app/';
                window.__MICRO_APP_BASE_ROUTE__ = '/react-app';
                window.microApp = window.parent.microApp;
              </script>
            `
            return code.replace('<head>', `<head>${injectScript}`)
          }
        }
      ]
    }
  },
  // 全局配置
  shadowDOM: false,
  inline: true,
  disableSandbox: true,
  // 应用配置
  apps: [
    {
      name: 'child-app',
      url: 'http://localhost:3001/',
      baseRoute: '/child-app'
    },
    {
      name: 'react-app',
      url: 'http://localhost:3002/',
      baseRoute: '/react-app'
    }
  ]
})

const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(ElementPlus)
app.use(router)
app.mount('#app')